
import time
from src.face_align import norm_crop 
from src.utils import drawImg,is_point_near_segment
from src.global_dict import gd
import ast
import datetime
import cv2

def post_process_allbody(img_bgr, task_id, args, logger, yolo_face, face_recog, yolo11n_pose, rule_info_dict,frame_count, result_dic, id_dic):

    try:
        end_line = rule_info_dict.get('end_line', [])
        end_line_list = ast.literal_eval(end_line)
    except (ValueError, SyntaxError) as e:
        logger.error(f"Error parsing end_line: {e}")
        return

    dbase_name = gd.rule_info_dict[task_id].get('dbase_name', 'stream_test')
    add_stranger = gd.rule_info_dict[task_id].get('add_stranger', 0)
    alert_time = int(gd.rule_info_dict[task_id].get('alert_time', '1'))
    DISTANCE_THRESHOLD = 300
    
    id_list = []
    person_msg = {}
    t1 = time.time()
    results = yolo11n_pose.track(img_bgr,imgsz=640, tracker="bytetrack.yaml", persist=True, device=0, iou=0.7, conf=0.25, verbose=False) 
    # results = yolo11n_pose(img_bgr,imgsz=640, device=0, iou=0.7, conf=0.25, verbose=False)  # predict on an image
    t2 = time.time()
    # annotated_frame = results[0].plot()
    # cv2.imwrite('img/' + str(frame_count) + '.jpg', annotated_frame)
    
    
    # Access the results
    # print('person_number: ', len(results[0]))

    frame_id = []

    for result in results[0]:
        xy = result.keypoints.xy.cpu().numpy().tolist()[0]  # x and y coordinates
        xyn = result.keypoints.xyn.cpu().numpy().tolist()[0]  # normalized
        kpts = result.keypoints.data.cpu().numpy().tolist()[0]  # x, y, visibility (if available)

        if result.boxes is None or result.boxes.id is None:
            continue

        xyxy = result.boxes.xyxy.cpu().numpy().tolist()[0]
        track_id = result.boxes.id.int().cpu().tolist()[0]
        x1,y1,x2,y2 = xyxy

        img_c_point = []
        foot_point = []

        person_msg = {}
      
        # 计算中心点坐标
        cx = int((x1 + x2) / 2)
        cy = int((y1 + y2) / 2)

        down_c_point = (cx,y2)

        # print(down_c_point)

        img_c_point.append((cx,cy))
        foot_point = [xy[16], xy[15], down_c_point]

        frame_id.append(track_id)

        

        

        if track_id not in id_dic:

            img_bgr_body = img_bgr[int(y1):int(y2),int(x1):int(x2)]

            id_dic[track_id] = {}
            id_dic[track_id]['name'] = 'stranger'
            id_dic[track_id]['img'] = img_bgr_body


        if 'stranger' in id_dic[track_id]['name']: 

            img_bgr_body = img_bgr[int(y1):int(y2),int(x1):int(x2)]

            bboxes_face, kpss = yolo_face.detect(img_bgr_body, args.face_detec_thres2)
            name = 'stranger'
            for (bbox_face, kps) in zip(bboxes_face, kpss):
                face_bgr = norm_crop(img_bgr_body, kps)
                
                features, norms = face_recog.get_features([face_bgr])
                name, conf = face_recog.top1(dbase_name, features[0], add_stranger)
                # print(name)


            id_dic[track_id]['name'] = name
        
        


    
            
    result_dic.append(frame_id)



    if len(result_dic) == 75:

        first_array = result_dic[0]
        rest_arrays = result_dic[1:]

        for num in first_array:
            if all(num not in arr for arr in rest_arrays):
                save_img = id_dic[num]['img']
                save_img_name = id_dic[num]['name']

                end_t = time.time()
                end_t_datetime = datetime.datetime.fromtimestamp(end_t)  # 将时间戳转换为datetime对象
                formatted_end_t = end_t_datetime.strftime('%Y_%m_%d_%H_%M_%S_%f')  # 格式化datetime对象为指定字符串格式


                person_msg['name']=name

                person_msg['end_t']=formatted_end_t


                logger.info(f'task id: {task_id}, end_person_msg:{person_msg} ------')

                    

                cv2.imwrite('all_body/' + str(save_img_name) + '_' + str(formatted_end_t) + '.jpg', save_img)



                



        

        result_dic.pop(0)

   

    # print(id_dic) 

    

    

    

        


           








        

                

                
                


   

    
    t6 = time.time()

    cost = t6 - gd.lastt_dict[task_id]
    gd.lastt_dict[task_id] = t6

   